<script setup lang="ts">
import { ref } from 'vue'
import KnowledgeCard from './KnowledgeCard.vue'
import { getKnowledgePage } from '@/services/consult'
import type { KnowledgeType, KnowledgeParams } from '@/types/consult'
import type { KnowledgeList } from '@/types/consult'

const props = defineProps<{
  type: KnowledgeType
}>()

const loading = ref(false)
const finished = ref(false)

const list = ref<KnowledgeList>([])

const params = ref<KnowledgeParams>({
  type: props.type, // 类型
  current: 1, // 页码
  pageSize: 10 // 每页条数
})

// case1: 初始化的时候会触发（前提：这个内容没有占满一屏）
// case2: 触底的时候会触发
const onLoad = async () => {
  // !#1 调用真实接口
  const r = await getKnowledgePage(params.value)
  list.value.push(...r.data.rows)
  // !#2 判断加载完毕的逻辑
  if (params.value.current >= r.data.pageTotal) {
    finished.value = true
  } else {
    params.value.current++
  }
  // !#3 加载数据完毕了，van-list 内部会把 loading 置为 true，我们要再置为 false 继续加载
  loading.value = false
}
</script>

<template>
  <div class="knowledge-list">
    <!-- 想让哪一块有上拉触底的效果，就用 van-list 包裹一下 -->
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <knowledge-card
        v-for="item in list"
        :key="item.id"
        :item="item"
      ></knowledge-card>
    </van-list>
  </div>
</template>

<style lang="scss" scoped>
.knowledge-list {
  padding: 0 15px;
}
</style>
